﻿
using System ;


namespace MskEdit.Sdk
{
    static public class SdkSubstring 
    {

        private static bool IsValidSubstring( string str, SdkSubrange subrange ) {
        
            if ( string.IsNullOrEmpty( str ) )
                return false ;
    
            if ( ! subrange.IsSubrangeOf( str.Length ) )
                return false ;
                
            return true ;
        }


        public static string TryLeftFrom( string str, SdkSubrange subrange, string fallback ) {
        
            if ( ! IsValidSubstring( str, subrange ) )
                return fallback ;
                
            return str.Substring( 0, subrange.Start ) ;
        }
  

        public static string TryFrom( string str, SdkSubrange subrange, string fallback ) {
        
            if ( ! IsValidSubstring( str, subrange ) )
                return fallback ;
                
            return str.Substring( subrange.Start, subrange.Length ) ;
        }
        

        public static string TryRightFrom( string str, SdkSubrange subrange, string fallback ) {
        
            if ( ! IsValidSubstring( str, subrange ) )
                return fallback ;
                
            int rightStartIndex = subrange.Start + subrange.Length ;
            int rightLength     = str.Length - rightStartIndex ;
            
            return str.Substring( rightStartIndex , rightLength  ) ;
        }
        
        
        public static string TryInsert( string str, SdkSubrange subrange, string sstr, string fallbackValue ) {
        
            if ( ! IsValidSubstring( str, subrange ) )
                return fallbackValue ;
                
            if ( string.IsNullOrEmpty( sstr ) )
                return fallbackValue ;
                
            if ( ! ( sstr.Length <= subrange.Length ) )
                return fallbackValue ;
                
            string leftStr  = TryLeftFrom( str, subrange, null ) ;
            if ( leftStr == null )
                return fallbackValue ;

            string subStr   = sstr.PadRight( subrange.Length ).Substring( 0, subrange.Length ) ;

            string rightStr = TryRightFrom( str, subrange, null ) ;
            if ( rightStr == null )
                return fallbackValue ;
            
            string newStr = leftStr + subStr + rightStr ;
                
            return newStr ;
        }
  
    }
}
